<template>
  <div v-if="showDialog" class="file-preview-dialog" @click="handleClose">
    <div class="file-preview-content" @click.stop>
      <!-- 关闭按钮 -->
      <div class="close-btn" @click="handleClose">
        <el-icon>
          <close />
        </el-icon>
      </div>
      <!-- 左右切换按钮 -->
      <div v-if="props.fileList.length > 1" class="nav-btn nav-btn-left" @click="handlePrevFile">
        <el-icon>
          <arrow-left />
        </el-icon>
      </div>
      <div v-if="props.fileList.length > 1" class="nav-btn nav-btn-right" @click="handleNextFile">
        <el-icon>
          <arrow-right />
        </el-icon>
      </div>
      <!-- 文件内容展示区域 -->
      <div class="file-box">
        <FileDisplay
          :file-src="currentFile.src"
          :file-name="currentFile.name"
          :file-type="currentFile.filetype"
          :active-sheet-name="activeSheetName"
          :xls-data="xlsData"
          :txt-data="txtData"
          @sheet-change="handleSheetChange"
        />
      </div>

      <!-- 文件信息和操作按钮 -->
      <div class="file-info-bar">
        <div class="file-info">
          <span class="file-name">{{ currentFile.name || extractFileName(currentFile.src) }}</span>
          <span class="file-index">{{ currentIndex + 1 }} / {{ props.fileList.length }}</span>
        </div>
        <div class="file-actions">
          <button class="action-btn" @click="handleDownload">
            <i class="el-icon-download"></i> 下载
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="PreviewDialog">
import { ref, defineProps, defineEmits, watch } from "vue"
import FileDisplay from "./FileDisplay.vue"
import { extractFileName, getFileArrayBufferBySrc, downloadFile } from "./fileUtils"
import * as XLSX from "xlsx-js-style"

/**
 * 组件属性定义
 */
const props = defineProps({
  // 是否显示对话框
  showDialog: {
    type: Boolean,
    default: false
  },
  // 文件列表
  fileList: {
    type: Array,
    required: true
  },
  // 初始文件路径
  initialSrc: {
    type: String,
    default: ""
  }
})

/**
 * 组件事件定义
 */
const emit = defineEmits([
  "close" // 关闭对话框
])

// 响应式数据
const activeSheetName = ref(undefined)
const xlsData = ref({})
const txtData = ref(undefined)
const currentIndex = ref(0)

// 当前文件
const currentFile = ref({})

/**
 * 重置数据
 */
const resetData = () => {
  activeSheetName.value = undefined
  xlsData.value = {}
  txtData.value = undefined
}

/**
 * 监听对话框显示状态和初始文件
 */
watch(
  () => [props.showDialog, props.initialSrc],
  ([show, initialSrc]) => {
    if (show) {
      // 找到初始文件在列表中的索引
      const foundIndex = props.fileList.findIndex(file => file.src === initialSrc)
      currentIndex.value = foundIndex !== -1 ? foundIndex : 0

      if (props.fileList[currentIndex.value]) {
        currentFile.value = props.fileList[currentIndex.value]
        loadCurrentFile()
      }
    } else {
      // 重置数据
      resetData()
    }
  },
  { immediate: true }
)

/**
 * 加载当前文件内容（仅处理需要特殊加载的文件类型）
 */
const loadCurrentFile = async () => {
  if (!currentFile.value) return

  // 重置数据
  resetData()

  try {
    // 处理Excel文件(.xls)
    if (currentFile.value.filetype === "xls") {
      const arrayBuffer = await getFileArrayBufferBySrc(currentFile.value.src, false)
      const data = new Uint8Array(arrayBuffer)
      const workbook = XLSX.read(data, { type: "buffer" })
      activeSheetName.value = workbook.SheetNames[0]
      workbook.SheetNames.forEach(sheetName => {
        const worksheet = workbook.Sheets[sheetName]
        xlsData.value[sheetName] = XLSX.utils.sheet_to_json(worksheet)
      })
    }
    // 处理文本文件(.txt)
    else if (currentFile.value.filetype === "txt") {
      const arrayBuffer = await getFileArrayBufferBySrc(currentFile.value.src, false)
      const decoder = new TextDecoder("utf-8")
      txtData.value = decoder.decode(arrayBuffer)
    }
  } catch (error) {
    console.error("加载文件失败:", error)
  }
}

/**
 * 处理关闭对话框
 */
const handleClose = () => {
  emit("close")
}

/**
 * 处理上一个文件
 */
const handlePrevFile = () => {
  if (props.fileList.length <= 1) return
  currentIndex.value = currentIndex.value > 0 ? currentIndex.value - 1 : props.fileList.length - 1
  currentFile.value = props.fileList[currentIndex.value]
  loadCurrentFile()
}

/**
 * 处理下一个文件
 */
const handleNextFile = () => {
  if (props.fileList.length <= 1) return
  currentIndex.value = currentIndex.value < props.fileList.length - 1 ? currentIndex.value + 1 : 0
  currentFile.value = props.fileList[currentIndex.value]
  loadCurrentFile()
}

/**
 * 处理Excel工作表切换
 * @param {string} sheetName - 工作表名称
 */
const handleSheetChange = sheetName => {
  activeSheetName.value = sheetName
}

/**
 * 处理文件下载
 */
const handleDownload = () => {
  const fileName = currentFile.value.name || extractFileName(currentFile.value.src)
  downloadFile(currentFile.value.src, fileName)
}
</script>

<style lang="scss" scoped>
$border-color: #e4e7ed;
$active-color: #409eff;
$nav-btn-size: 44px;

.file-preview-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;

  .file-preview-content {
    width: 90vw;
    height: 90vh;
    background-color: #fff;
    border-radius: 8px;
    position: relative;
    display: flex;
    flex-direction: column;

    // 关闭按钮
    .close-btn {
      position: absolute;
      top: 15px;
      right: 15px;
      width: 32px;
      height: 32px;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      cursor: pointer;
      z-index: 10;
      transition: background-color 0.3s;

      &:hover {
        background-color: rgba(0, 0, 0, 0.7);
      }

      i {
        font-size: 16px;
      }
    }

    // 左右切换按钮
    .nav-btn {
      position: absolute;
      top: 50%;
      width: $nav-btn-size;
      height: $nav-btn-size;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 3px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      cursor: pointer;
      z-index: 100;
      transition: all 0.3s;

      &:hover {
        background-color: rgba(0, 0, 0, 0.7);
        transform: scale(1.1);
      }

      i {
        font-size: 18px;
      }

      &.nav-btn-left {
        left: 20px;
      }

      &.nav-btn-right {
        right: 20px;
      }
    }

    // 文件内容区域
    .file-box {
      flex: 1;
      padding: 20px 40px;
      overflow: hidden;
    }

    // 文件信息栏
    .file-info-bar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 20px;
      border-top: 1px solid $border-color;
      background-color: #f8f9fa;

      .file-info {
        display: flex;
        align-items: center;
        gap: 15px;

        .file-name {
          font-weight: 500;
          color: #303133;
        }

        .file-index {
          color: #909399;
          font-size: 14px;
        }
      }

      .file-actions {
        .action-btn {
          background-color: $active-color;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
          transition: background-color 0.3s;

          &:hover {
            background-color: darken($active-color, 10%);
          }

          i {
            margin-right: 4px;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .file-preview-dialog {
    .file-preview-content {
      width: 95vw;
      height: 95vh;

      .nav-btn {
        width: 36px;
        height: 36px;

        &.nav-btn-left {
          left: 10px;
        }

        &.nav-btn-right {
          right: 10px;
        }
      }

      .file-box {
        padding: 10px;
      }

      .file-info-bar {
        padding: 10px 15px;

        .file-info {
          gap: 10px;

          .file-name {
            max-width: 150px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>